// 画图类
class Displayer {
  points;
  traj;
  curIndex;
  ctxG;
  ctxL;
  background;
  width;
  height;
  done = false;
  constructor(traj, ctxG, ctxL, width, height, bgImage) {
    this.traj = traj;
    this.points = new Array(100);
    this.curIndex = 0;
    this.ctxG = ctxG;
    this.ctxL = ctxL;
    this.width = width;
    this.height = height;
    this.bgImage = bgImage;

    const xOffset = (this.bgImage.width - 300) / 100;
    const yOffset = (this.bgImage.height - 300) / 100;
    const xCenter = (this.bgImage.width - 300) / 2 - 150;
    const yCenter = (this.bgImage.height - 300) / 2 + 150;
    if (this.traj === "horizontal") {
      for (let i = 0; i < 100; i++) {
        this.points[i] = [xOffset * i, yCenter - 150];
      }
    }
    if (this.traj === "vertical") {
      for (let i = 0; i < 100; i++) {
        this.points[i] = [xCenter + 150, yOffset * i];
      }
    }
    if (this.traj === "diagonal") {
      for (let i = 0; i < 100; i++) {
        this.points[i] = [xOffset * (i + 1), yOffset * i];
      }
    }
  }
  displayNextFrame() {
    this.displayGlobalView();
    this.displayLocalView();
    this.nextPoint();
  }
  displayGlobalView() {
    this.ctxG.clearRect(0, 0, this.width, this.height);
    const xScale = this.width / this.bgImage.width;
    const yScale = this.height / this.bgImage.height;
    this.ctxG.drawImage(this.bgImage, 0, 0, this.width, this.height);
    this.ctxG.strokeStyle = "red";
    this.ctxG.lineWidth = 2;
    const x = this.points[this.curIndex][0];
    const y = this.points[this.curIndex][1];
    this.ctxG.strokeRect(x * xScale, y * yScale, 300 * xScale, 300 * yScale);
  }
  displayLocalView() {
    this.ctxL.clearRect(0, 0, this.width, this.height);
    const xs = this.points[this.curIndex][0];
    const ys = this.points[this.curIndex][1];
    this.ctxL.drawImage(
      this.bgImage,
      xs,
      ys,
      300,
      300,
      0,
      0,
      this.width,
      this.height
    );
  }
  nextPoint() {
    if (this.curIndex === this.points.length - 1) {
      this.done = true;
    } else {
      this.curIndex++;
    }
  }
  getPercentage() {
    return Math.floor(((this.curIndex + 1) / this.points.length) * 100);
  }
}

// 检验IP地址
function isValidIP(ip) {
  const reg =
    /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
  return reg.test(ip);
}
// 检验端口号
function isValidPort(port) {
  const num = Number(port);
  return num >= 1024 && num <= 65535;
}
export { Displayer, isValidIP, isValidPort };
